<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-7-25
 * Time: 下午9:33
 */

namespace home\models;


use common\models\db\User;
use yii\base\Model;

class FormResetPassword extends Model
{
    public $email;
    public $password;
    public $repassword;
    public $code;

    public function attributeLabels()
    {
        return [
            'email' => "邮箱",
            'password' => "密码",
            'repassword' => "重复密码",
            'code' => "验证码",
        ];
    }

    public function rules()
    {
        return [
            [['email'], 'trim'],
            [['email', 'password', 'code'], 'required'],
            [['email'], 'string', 'max' => 200],
            ['email', 'email'],
            ['email', 'exist', 'targetClass' => User::class, 'targetAttribute' => 'email'],
            ['password', 'string', 'min' => 6, 'max' => 20],
            ['repassword', 'compare', 'compareAttribute' => 'password'],
            ['code', 'string', 'min' => 4, 'max' => 4],
            ['code', 'captcha'],
        ];
    }

    public function reset()
    {
        $user = User::findOne(['email' => $this->email]);
        if (!$user){
            \Yii::$app->session->setFlash("error", "没有这个邮箱的账户，请注册！");
            return \Yii::$app->controller->redirect(['site/signup']);
        }
        if ($user->status != $user::STATUS_ACTIVE){
            \Yii::$app->session->setFlash("error", "账户未激活，请先激活！");
            return \Yii::$app->controller->redirect(['site/resend-active-link-for-email']);
        }
        $code = $user->generateCode($user::RESET_PASSWORD_CODE_PRE);
        if (!$user->setCacheData($this->password, $user::PASSWORD_STORE_PRE)){
            \Yii::$app->session->setFlash("error", "缓存异常！");
            return \Yii::$app->controller->redirect(['site/reset-password']);
        }
        $link = \Yii::$app->urlManager->createAbsoluteUrl(['site/do-reset-password', 'email'=>$this->email, 'code'=>$code]);
        $html = \Yii::$app->controller->renderPartial('/emails/reset-password', ['link' => $link]);
        $bool = \Yii::$app->mailer->compose()->setTo($this->email)->setSubject("重置密码链接")->setHtmlBody($html)->send();
        if ($bool){
            \Yii::$app->session->setFlash('success', "发送成功，请去邮箱确认重置密码。");
            return \Yii::$app->controller->redirect(['site/login']);
        }else{
            \Yii::$app->session->setFlash('error', "发送邮件失败！");
            return \Yii::$app->controller->redirect(['site/resend-active-link-for-email']);
        }
    }
}